package handler

import (
	"context"
	"github.com/zachary/tbox/internal/svc"
	"github.com/zachary/tbox/internal/web/util"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

func BaseHandler[T any](v *T, do func(v *T) *util.R) http.HandlerFunc {
	return func(writer http.ResponseWriter, request *http.Request) {
		if err := httpx.Parse(request, v); err != nil {
			httpx.ErrorCtx(request.Context(), writer, err)
			return
		}
		httpx.OkJson(writer, do(v))
	}
}

func BaseHandlerWithCtx[T any](serverCtx *svc.ServiceContext, v *T,
	do func(serverCtx *svc.ServiceContext, reqCtx context.Context, v *T) *util.R) http.HandlerFunc {
	return func(writer http.ResponseWriter, request *http.Request) {
		if err := httpx.Parse(request, v); err != nil {
			httpx.ErrorCtx(request.Context(), writer, err)
			return
		}
		httpx.OkJson(writer, do(serverCtx, request.Context(), v))
	}
}
